//
//  MapViewController.m
//  Travel
//
//  Created by lanou3g on 15/12/9.
//  Copyright © 2015年 涂晓雨. All rights reserved.
//

#import "MapViewController.h"
#import "PlayTableViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import <AMapSearchKit/AMapSearchKit.h>
@interface MapViewController ()<MKMapViewDelegate,AMapSearchDelegate,UISearchBarDelegate>
@property(nonatomic,strong)UIButton *button;
@property(nonatomic,strong)UIButton *button1;
@property(nonatomic,strong)MKMapView *mapView;
@property(nonatomic,strong)CLGeocoder *gecoder;
@property(nonatomic,strong)AMapSearchAPI *search;
@property(nonatomic,strong)UISearchBar *seachBar;
@property(nonatomic,strong)AMapInputTipsSearchRequest *request;
@end

@implementation MapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addMap];
    self.seachBar = [[UISearchBar alloc]initWithFrame:CGRectMake(10, 40, self.view.frame.size.width - 20, 50)];
    self.seachBar.delegate = self;
    self.seachBar.keyboardType = UIKeyboardAppearanceDefault;
    self.seachBar.translucent = YES;
    [self.mapView addSubview:self.seachBar];
    
    [AMapSearchServices sharedServices].apiKey = @"7cec5047f0153b6e6b756581eda6d250";
    
   
    [self dismissButton];
    [self returnButton];
    
    self.gecoder = [[CLGeocoder alloc]init];

    self.mapView.delegate = self;
    
    [self.mapView setCenterCoordinate:self.mapView.userLocation.location.coordinate animated:YES];

    [self getCoordinateByAddress:self.city];
    
    [self searchAddress];
}


-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{

    

}



-(void)searchAddress{

    //初始化搜索对象
    _search = [[AMapSearchAPI alloc]init];
    _search.delegate = self;
    
   self.request = [[AMapInputTipsSearchRequest alloc]init];
    //self.request.location = [AMapGeoPoint locationWithLatitude:self.mapView.userLocation.coordinate.latitude longitude:self.mapView.userLocation.coordinate.longitude];
    self.request.keywords = self.seachBar.text;
    self.request.city = self.city;
    self.request.types = @"餐饮服务|生活服务|风景名胜|住宿服务|购物服务";
    [_search AMapInputTipsSearch:self.request];
  

}

/* 清除annotations & overlays */
- (void)clear
{
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView removeOverlays:self.mapView.overlays];
}

//实现输入提示的回调函数
-(void)onInputTipsSearchDone:(AMapInputTipsSearchRequest*)request response:(AMapInputTipsSearchResponse *)response
{
    if(response.tips.count == 0)
    {
        return;
    }
    
    //通过AMapInputTipsSearchResponse对象处理搜索结果
    NSString *strCount = [NSString stringWithFormat:@"count: %d", response.count];
    NSString *strtips = @"";
    for (AMapTip *p in response.tips) {
        strtips = [NSString stringWithFormat:@"%@\nTip: %@", strtips, p.description];
    }
    NSString *result = [NSString stringWithFormat:@"%@ \n %@", strCount, strtips];
    NSLog(@"InputTips: %@", result);
}
//是否开启定位功能
-(void)viewWillAppear:(BOOL)animated{
    
    if (![CLLocationManager  locationServicesEnabled]) {
        
        UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"提示" message:@"请开启GPS" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alter animated:YES completion:nil];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alter addAction:action];
    }
}

//添加地图
-(void)addMap{
    //设置地图
    self.mapView = [[MKMapView alloc]initWithFrame:self.view.bounds];
    //设置地图的类型
    self.mapView.mapType = MKMapTypeStandard;
    //是否展示
    self.mapView.showsUserLocation = YES;
    //添加
    [self.view addSubview: self.mapView];
    //是否对用户进行位置跟踪(位置和方向同时进行跟踪)
    self.mapView.userTrackingMode = MKUserTrackingModeNone;
    _mapView.showsBuildings = YES;
    _mapView.shouldGroupAccessibilityChildren = YES;
}



//用户位置跟踪  用户位置发生改变时触发（第一次定位到用户位置也会触发该方法）
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(nonnull MKUserLocation *)userLocation{

    [self.mapView setCenterCoordinate:self.mapView.userLocation.coordinate animated:YES];
    //设置精确度
    MKCoordinateSpan span = MKCoordinateSpanMake(0.1, 0.1);
    MKCoordinateRegion region = MKCoordinateRegionMake(self.mapView.userLocation.location.coordinate, span);
    [self.mapView setRegion:region];
}


//地理编码  （根据城市的名称来确定地理位置）
-(void)getCoordinateByAddress:(NSString *)city{
    //地理编码
    [self.gecoder geocodeAddressString:city completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        //取得第一个地标 地标存储了详细的地址信息 注意一个地名可以搜索出多个地址
        CLPlacemark *placeMark = [placemarks firstObject];
        //位置的跳转
       // [self.mapView setCenterCoordinate:placeMark.location.coordinate animated:YES];
        self.mapView.showsUserLocation = NO;
//        //取得第一个地标 地标存储了详细的地址信息 注意一个地名可以搜索出多个地址
//        CLPlacemark *placeMark = [placemarks firstObject];
//        //将定位坐标转换为地图的坐标
//        MKPlacemark *mkPlace = [[MKPlacemark alloc]initWithPlacemark:placeMark];
//        //定义地图的类型
//        NSDictionary *options = @{MKLaunchOptionsMapTypeKey:@(MKMapTypeStandard)};
//        MKMapItem *mapItem = [[MKMapItem alloc]initWithPlacemark:mkPlace];
//        [mapItem openInMapsWithLaunchOptions:options];
//        self.mapView.showsUserLocation = NO;
        
        CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(placeMark.location.coordinate.latitude, placeMark.location.coordinate.longitude);
        float zoomlevel = 0.1;
        MKCoordinateRegion region = MKCoordinateRegionMake(coords, MKCoordinateSpanMake(zoomlevel, zoomlevel));
        [_mapView setRegion:region animated:YES];
        
        MKPointAnnotation *pAnn = [[MKPointAnnotation alloc]init];
        pAnn.coordinate = placeMark.location.coordinate;
        [_mapView addAnnotation:pAnn];
    }];

}




//返回的button
-(void)dismissButton{
    
    self.button = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width - 70, self.view.frame.size.height - 100, 50, 50)];
    self.button.layer.masksToBounds = YES;
    self.button.layer.cornerRadius = 25;
    self.button.backgroundColor = [UIColor redColor];
    [self.mapView addSubview:self.button];
    [self.mapView bringSubviewToFront:self.button];
    [self.button  addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];

}

 //回到当前所在的地理位置的button
-(void)returnButton{
    
    self.button1 = [[UIButton alloc]initWithFrame:CGRectMake(20, self.view.frame.size.height - 100, 50, 50)];
    self.button1.layer.masksToBounds = YES;
    self.button1.layer.cornerRadius = 25;
    self.button1.backgroundColor = [UIColor redColor];
    [self.mapView addSubview:self.button1];
    [self.mapView bringSubviewToFront:self.button1];
    [self.button1  addTarget:self action:@selector(action1) forControlEvents:UIControlEventTouchUpInside];

}


//返回
-(void)action{

    [self dismissViewControllerAnimated:YES completion:nil];
}

//返回到当前所在的位置
-(void)action1{
    
    
    [self.mapView setCenterCoordinate:self.mapView.userLocation.location.coordinate animated:YES];
    self.mapView.showsUserLocation = YES;
  
}



@end
